<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 左侧菜单树 -->
      <el-col :span="6">
        <el-card class="box-card">
          <div slot="header">
            <span>菜单树</span>
            <el-button
              type="text"
              style="float: right"
              icon="el-icon-plus"
              @click="handleViewFirst"
            >
              查看一级
            </el-button>
          </div>
          <el-tree
            :data="treeData"
            node-key="id"
            :props="defaultProps"
            default-expand-all
            highlight-current
            @node-click="handleNodeClick"
          />
        </el-card>
      </el-col>

      <!-- 右侧表格 -->
      <el-col :span="18">
        <el-collapse-transition>
          <el-card v-show="isFilterVisible" class="search-wrapper">
            <el-form :inline="true" :model="menuListQuery">
              <el-form-item label="菜单名称">
                <el-input
                  v-model="menuListQuery.name"
                  clearable
                  placeholder="请输入菜单名称"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleQuery">查询</el-button>
                <el-button @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </el-collapse-transition>
        <el-card>
          <div>
            <div class="table-operations">
              <el-button
                type="primary"
                size="small"
                class="filter-trigger"
                @click="isFilterVisible = !isFilterVisible"
              >{{ isFilterVisible ? "收起" : "检索" }}
                <i
                  :class="[
                    'el-icon-arrow-down',
                    { 'is-reverse': isFilterVisible },
                  ]"
                />
              </el-button>
              <el-button
                type="primary"
                size="small"
                icon="el-icon-plus"
                @click="handleAdd"
              >新建</el-button>
              <el-button
                type="danger"
                size="small"
                icon="el-icon-delete"
                @click="handleBatchDelete"
              >批量删除</el-button>
              <!-- <el-dropdown style="float: right">
                <el-button size="small">
                  更多操作<i class="el-icon-arrow-down el-icon--right"></i>
                </el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item>导入</el-dropdown-item>
                  <el-dropdown-item>导出</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown> -->
            </div>

            <el-table
              :data="subMenuList"
              border
              @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column
                prop="number"
                label="编号"
                width="80"
              />
              <el-table-column prop="name" label="菜单名称" />
              <el-table-column prop="url" label="菜单地址" />
              <el-table-column
                prop="parentMenu"
                label="父级菜单"
              />
              <el-table-column
                prop="isShow"
                label="是否显示"
                width="100"
                align="center"
              >
                <template slot-scope="scope">
                  <el-tag
                    :type="scope.row.isShow === 1 ? 'success' : 'danger'"
                  >{{ scope.row.isShow === 1 ? "显示" : "不显示" }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="150" align="center">
                <template slot-scope="scope">
                  <el-button
                    type="primary"
                    size="small"
                    @click="handleEdit(scope.row)"
                  >编辑</el-button>
                  <el-button
                    type="danger"
                    size="small"
                    @click="handleDelete(scope.row)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <!-- 分页 -->
          <el-row
            :gutter="10"
            style="margin-top: 20px"
            type="flex"
            justify="end"
          >
            <el-pagination
              background
              :current-page="menuListQuery.page"
              :page-sizes="[10, 20, 30, 40, 50]"
              :page-size="menuListQuery.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </el-row>
        </el-card>
      </el-col>
    </el-row>

    <!-- 新增对话框 -->
    <el-dialog
      title="新增"
      :visible.sync="dialogVisible"
      width="800px"
      @close="close"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-position="top"
      >
        <el-row :gutter="20">
          <!-- <el-col :span="12">
            <el-form-item label="编号:" prop="number">
              <el-input
                v-model="formData.number"
                placeholder="请输入编号"
              ></el-input>
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="菜单名称:" prop="name">
              <el-input
                v-model="formData.name"
                placeholder="请输入菜单名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="菜单地址:" prop="url">
              <el-input
                v-model="formData.url"
                placeholder="请输入菜单地址"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- <el-row :gutter="20"> -->

        <!-- <el-col :span="12">
            <el-form-item label="图标:" prop="icon">
              <el-input v-model="formData.icon" placeholder="请输入"></el-input>
            </el-form-item>
          </el-col> -->
        <!-- </el-row> -->

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="是否显示:">
              <el-radio-group v-model="formData.isShow">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="2">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="选项卡能否关闭:">
              <el-radio-group v-model="formData.isClose">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="2">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="拥有功能:">
              <el-checkbox-group
                v-model="formData.list"
                @change="handleCheckboxChange"
              >
                <el-checkbox
                  v-for="item in selFunctionLists"
                  :key="item.id"
                  :label="item.id"
                >
                  {{ item.name }}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSubmit">提交</el-button>
        <el-button @click="dialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog
      title="编辑"
      :visible.sync="editDialogVisible"
      width="800px"
      @close="close"
    >
      <el-form
        ref="editFormRef"
        :model="editFormData"
        :rules="rules"
        label-position="top"
      >
        <el-row :gutter="20">
          <!-- <el-col :span="12">
            <el-form-item label="编号:" prop="number">
              <el-input
                v-model="editFormData.number"
                placeholder="请输入编号"
              ></el-input>
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="菜单名称:" prop="name">
              <el-input
                v-model="editFormData.name"
                placeholder="请输入菜单名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="菜单地址:" prop="url">
              <el-input
                v-model="editFormData.url"
                placeholder="请输入菜单地址"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- <el-row :gutter="20"> -->

        <!-- <el-col :span="12">
            <el-form-item label="图标:" prop="icon">
              <el-input v-model="formData.icon" placeholder="请输入"></el-input>
            </el-form-item>
          </el-col> -->
        <!-- </el-row> -->

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="是否显示:">
              <el-radio-group v-model="editFormData.isShow">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="2">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="选项卡能否关闭:">
              <el-radio-group v-model="editFormData.isClose">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="2">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="拥有功能:">
              <el-checkbox-group
                v-model="editFormData.list"
                @change="handleCheckboxChange"
              >
                <el-checkbox
                  v-for="item in selFunctionLists"
                  :key="item.id"
                  :label="item.id"
                >
                  {{ item.name }}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleEditSubmit">提交</el-button>
        <el-button @click="editDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  selMenuListApi,
  addMenuApi,
  updateMenuByIdApi,
  selMenuByIdApi,
  delMenuByIdsApi,
  selFunctionListApi
} from '@/api/system'
import { processMenuData } from '@/utils/menuHelper'

export default {
  name: 'MenuManagement',
  data() {
    return {
      treeData: [],
      subMenuList: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      // 查询菜单功能列表
      menuListQuery: {
        page: 1,
        pageSize: 10,
        name: '',
        parentId: ''
      },
      id: '',
      // 表格数据
      tableData: [
        {
          menuId: '1',
          menuName: '首页',
          menuPath: '/Report/index',
          parentMenu: '1',
          isShow: true
        },
        {
          menuId: '100',
          menuName: '系统管理',
          menuPath: '',
          parentMenu: '1',
          isShow: true
        }
      ],
      // 总条数
      total: 10,
      // 选中的行
      selectedRows: [],
      isFilterVisible: false,
      dialogVisible: false,
      // 新增表单数据
      formData: {
        isClose: 1, // 是否可以关闭
        isShow: 1, // 是否显示
        list: [], // 拥有功能
        name: '',
        number: 1,
        parentId: '',
        url: ''
      },
      // 编辑表单数据
      editFormData: {
        isClose: '', // 是否可以关闭
        isShow: '', // 是否显示
        list: [], // 拥有功能
        name: '',
        number: 1,
        parentId: '',
        url: '',
        id: ''
      },
      // 功能管理查询参数
      selFunctionListQuery: {
        page: 1,
        pageSize: 10,
        name: ''
      },
      editDialogVisible: false,
      selFunctionLists: [],
      selectedIds: [] // 批量删除
      // rules: {
      //   code: [{ required: true, message: "请输入编号", trigger: "blur" }],
      //   menuName: [
      //     { required: true, message: "请输入菜单名称", trigger: "blur" },
      //   ],
      // },
    }
  },
  created() {
    this.getMenuTree()
    this.selFunctionList()
  },
  methods: {
    // 查询功能列表
    async selFunctionList() {
      try {
        const res = await selFunctionListApi(this.selFunctionListQuery)
        console.log(res)
        this.selFunctionLists = res.records
      } catch (error) {
        console.error('获取功能列表失败:', error)
      }
    },
    // 功能选择变化
    handleCheckboxChange(val) {
      console.log(val)
    },
    // 查询子级菜单
    handleQuery() {
      this.menuListQuery.page = 1
      this.getSubMenuList()
    },
    // 获取菜单树数据
    async getMenuTree() {
      try {
        const res = await selMenuListApi()
        if (res.code === 1) {
          this.treeData = processMenuData(res.data)
        }
      } catch (error) {
        console.error('获取菜单树失败:', error)
      }
    },
    // 查看一级菜单
    handleViewFirst() {
      // 实现查看一级菜单逻辑
    },
    // 树节点点击
    async handleNodeClick(data) {
      console.log(data)
      this.menuListQuery.parentId = data.id
      // this.menuListQuery.name = data.name;
      console.log(this.menuListQuery)
      this.getSubMenuList()
    },
    // 子级菜单查询
    async getSubMenuList() {
      try {
        const res = await selMenuByIdApi(this.menuListQuery)
        console.log(res)
        this.subMenuList = res.records
        this.total = res.total
      } catch (error) {
        console.error('获取子菜单列表失败:', error)
      }
    },
    // 表格选择项变化
    handleSelectionChange(selection) {
      this.selectedRows = selection
      this.selectedIds = selection.map((item) => item.id)
    },
    // 新增
    handleAdd() {
      this.dialogVisible = true
    },
    // 编辑
    async handleEdit(row) {
      try {
        // 从返回的 functions 数组中提取 id，映射到 list 数组
        const functionIds = row.functions
          ? row.functions.map((func) => func.id)
          : []

        this.editFormData = {
          ...row,
          list: functionIds // 将功能ID数组赋值给list
        }
        this.id = row.id
        this.editDialogVisible = true
      } catch (error) {
        console.error('获取菜单详情失败:', error)
        this.$message.error('获取菜单详情失败')
      }
    },
    // 删除
    handleDelete(row) {
      this.$confirm('确认删除该菜单吗？', '提示', {
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      })
        .then(async() => {
          const res = await delMenuByIdsApi([row.id])
          if (res.code === 1) {
            this.$message.success('删除成功')
            this.getSubMenuList()
          } else {
            this.$message.error(res.msg)
          }
        })
        .catch(() => {})
    },
    // 批量删除
    handleBatchDelete() {
      if (this.selectedIds.length === 0) {
        this.$message.warning('请选择要删除的项目')
        return
      }
      this.$confirm(
        `确认删除选中的 ${this.selectedIds.length} 个菜单吗？`,
        '提示',
        {
          type: 'warning'
        }
      )
        .then(async() => {
          const res = await delMenuByIdsApi(this.selectedIds)
          if (res.code === 1) {
            this.$message.success('批量删除成功')
            this.getSubMenuList()
            this.selectedIds = []
          } else {
            this.$message.error(res.msg)
          }
        })
        .catch(() => {})
    },
    // 分页大小改变
    handleSizeChange(val) {
      this.queryParams.pageSize = val
      this.getList()
    },
    // 页码改变
    handleCurrentChange(val) {
      this.queryParams.pageNum = val
      this.getList()
    },
    // 新增提交
    async handleSubmit() {
      if (this.formData.name === '') {
        this.$message.warning('请输入菜单名称')
        return
      }
      try {
        const res = await addMenuApi({
          ...this.formData,
          parentId: this.menuListQuery.parentId,
          number: 1
        })
        if (res.code === 1) {
          this.$message.success('新增成功')
          this.dialogVisible = false
          this.formData = {
            isClose: 1, // 是否可以关闭
            isShow: 1, // 是否显示
            list: [], // 拥有功能
            name: '',
            number: 1,
            parentId: '',
            url: ''
          }
          this.getSubMenuList()
        } else {
          this.$message.error(res.msg)
        }
      } catch (error) {
        console.error('新增失败:', error)
      }
    },
    // 编辑提交
    async handleEditSubmit() {
      try {
        const valid = await this.$refs.editFormRef.validate()
        if (valid) {
          // 构建完整的提交数据
          const submitData = {
            name: this.editFormData.name, // 菜单名称
            number: 1, // 编号
            url: this.editFormData.url, // 菜单地址
            parentId: this.editFormData.parentId, // 父级ID
            isShow: this.editFormData.isShow, // 是否显示
            isClose: this.editFormData.isClose, // 是否可以关闭
            list: this.editFormData.list // 功能权限ID数组
          }

          const res = await updateMenuByIdApi(submitData, this.id)
          if (res.code === 1) {
            this.$message.success('更新成功')
            this.editDialogVisible = false
            this.getMenuTree() // 刷新菜单树
            this.getSubMenuList() // 刷新子菜单列表
          } else {
            this.$message.error(res.msg || '更新失败')
          }
        }
      } catch (error) {
        console.error('更新失败:', error)
        this.$message.error('更新失败')
      }
    },
    close() {
      this.$refs.formRef.resetFields()
      this.dialogVisible = false
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.box-card {
  margin-bottom: 20px;
}

.search-wrapper {
  margin-bottom: 16px;
}

/* .demo-form-inline {
  display: flex;
  justify-content: space-between;
} */

.filter-trigger .el-icon-arrow-down {
  margin-left: 5px;
  transition: transform 0.3s;
}

.filter-trigger .el-icon-arrow-down.is-reverse {
  transform: rotate(180deg);
}

.table-operations {
  margin-bottom: 16px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.left {
  display: flex;
  align-items: center;
}

.el-button + .el-button {
  margin-left: 8px;
}

.el-button--text {
  padding: 0 8px;
}

.el-checkbox-group {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.el-radio-group {
  display: flex;
  gap: 20px;
}

.el-form-item__label {
  padding-bottom: 8px;
}

.dialog-footer {
  text-align: right;
}

.dialog-footer .el-button {
  padding: 9px 20px;
}

/* 确保表单项标签和内容垂直排列 */
:deep(.el-form-item) {
  display: flex;
  flex-direction: column;
}

:deep(.el-form-item__label) {
  text-align: left;
  float: none;
}

:deep(.el-form-item__content) {
  margin-left: 0 !important;
}
</style>
